//
//  HJOauthViewController.swift
//  Micro-blog Sina
//
//  Created by admin on 16/3/21.
//  Copyright © 2016年 admin. All rights reserved.
//

import UIKit
import SVProgressHUD

class HJOauthViewController: UIViewController {
    override func loadView() {
        view = webView
        
        webView.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavigationBar()
        view.backgroundColor = UIColor.whiteColor()
        // Use webView to load the login interface
        
        let request = NSURLRequest(URL: HJNetworkTool.sharedInstance.oauthLoginUrl())
        webView.loadRequest(request)
    }
    
    // Setting navigationBar
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "自动", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
    }
    
    // MARK: - Button click event
    @objc private func autoFill() {
        let js = "document.getElementById('userId').value='hejia0218@sina.com';document.getElementById('passwd').value='dushalove521'"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    @objc private func cancel() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: - webView Lazy load
    private lazy var webView: UIWebView = UIWebView()
}

// MARK: - UIWebViewDelegate
extension HJOauthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在加载登录界面", maskType: SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        // Close tip
        SVProgressHUD.dismiss()
    }
    // webView加载失败时调用
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        print("error = \(error)")
        SVProgressHUD.dismiss()
        // error = Optional(Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline."
        if error?.code != 102 {
            SVProgressHUD.showErrorWithStatus("加载失败", maskType: SVProgressHUDMaskType.Black)
        }
        
    }
    /**
     Whether to load a URL
     
     - parameter webView:        webView
     - parameter request:        request
     - parameter navigationType: navigationType
     
     - returns: return true express load / return false express not load
     */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request)
        let urlString = request.URL!.absoluteString
        // 如果加载的不是授权回调页面,直接加载网页,
        // 如果加载的是授权回调页面,对后面的参数进行判断,如果有code=表示点击了授权按钮,否则点击取消
        // To determine whether the callback address
        if !urlString.hasPrefix(redirect_uri) {
            return true
        }
        print("回调地址: \(request.URL?.query)")
        // To judge whether the following parameters
        if let query = request.URL?.query {
            let newQuery = query as NSString
            let codeString = "code="
            // To determine whether the query which contains the 'code=' string
            if newQuery.hasPrefix(codeString) {
                let code = newQuery.substringFromIndex(codeString.characters.count)
                print("code = \(code)")
                // 模型不需要关心怎么加载和保存AccessToken
                HJUserAccountViewModel.sharedInstance.loadAccessToken(code, completion: { (error) -> () in
                    if error != nil {
                        print("加载accessToken出错: \(error)")
                        SVProgressHUD.showErrorWithStatus("您的网络不给力", maskType: SVProgressHUDMaskType.Black)
                        // 延迟1秒再关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)),dispatch_get_main_queue(), { () -> Void in
                            // 关闭授权控制器
                            self.cancel()
                        })
                        return
                    }
                    // 直接关闭控制器
                    print("加载accessToken完成")
                    AppDelegate.outSwitchRootViewController(false)
                    self.cancel()
                })
            }else {
                // cancel
                cancel()
            }
        }
        return false
    }
}
